#include "cscene.h"
#include "cmd_parse/json_device_object.h"

CScene::CScene(QObject *parent) :
    CKnxControl(parent)
{
}

void CScene::setKnxObject(void *jOBJECT)
{
    //表达式状态
    Json_DEVICE_OBJECT *object = (Json_DEVICE_OBJECT *)jOBJECT;

    //发送值
    QStringList arrys = object->_send.split(";");
    if(arrys.size()>=1)
    {
        QString sonArray = arrys.at(0);
        _sendUpArray = sonArray.split(",");
    }
}

void CScene::setKnxObjectBySend(QString send)
{
    //发送值
    QStringList arrys = send.split(";");
    if(arrys.size()>=1)
    {
        QString sonArray = arrys.at(0);
        _sendUpArray = sonArray.split(",");
    }
}

void CScene::readKnxAction()
{
    qDebug() << "CScene: should not read the status";
}

void CScene::execKnxAction(QString action,QString value)
{
    QStringList *sendArray = &_sendUpArray;

    CKnxExecThread *eThread = new CKnxExecThread();
    eThread->ttgConnector = (CTTGIpsConnector *)cntDelegate;

    connect(eThread,SIGNAL(finished()),eThread,SLOT(deleteLater()));

    QString sendAddress,sendValue;
    DATA_TYPE sendDataType;
    DATA_DEFINE sendValueDefine;

    for (int i=0; i<sendArray->size(); i++)
    {
        QString dev = sendArray->at(i);
        QStringList devArray = dev.split(":");

        if (devArray.size() > 3) {

            sendAddress = devArray.at(0);

            if (sendAddress == "msleep") {
                CExecStruct *s = new CExecStruct();
                s->address = dev;

                eThread->execList.append(s);
            }
            else
            {
                sendDataType = (DATA_TYPE)devArray.at(1).toUInt();
                sendValueDefine = (DATA_DEFINE)devArray.at(2).toUInt();
                sendValue = devArray.at(3);

                if(!sendAddress.isEmpty())
                {
                    int data_len = 0;
                    memset(_data_buf,0,sizeof(_data_buf));

                    if((data_len = DEVICE_OBJECT::KnxQStringToData(sendValue,sendDataType,sendValueDefine,(_u8 *)_data_buf)) == -1)
                    {
                        qDebug() << "SetDev ret='-1' msg='error data args'" ;
                        continue ;
                    }

                    CExecStruct *s = new CExecStruct();
                    s->address = sendAddress;
                    s->type = sendDataType;
                    s->data = QByteArray((const char *)_data_buf,data_len);

                    eThread->execList.append(s);
                }
            }

        }
    }

    eThread->start();

}

QString CScene::actionFromStatus(QString address,QString value)
{
   return "null";
}

void CScene::execDeviceAction(QString action,QString value,QString unit)
{
    execKnxAction("on",value);
}
